<template>
  <!-- 柱状图 -->
  <div ref="chartRef" :style="{ height: '100%' }"></div>
</template>
<script lang="ts" setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts'

interface Props {
  chartData: {
    xAxisData: string[]
    seriesData: {
      name: string
      data: number[]
    }[]
  }
}
const props = withDefaults(defineProps<Props>(), {})
const chartRef = ref<HTMLDivElement | null>(null)
let chartInstance: echarts.ECharts | null = null
// 初始化图表
onMounted(() => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
    initChart()
  }
})
watch(
  () => [props.chartData],
  async () => {
    if (chartInstance) {
      initChart()
    }
  },
  { deep: true }
)

const initChart = () => {
  const option: echarts.EChartsOption = {
    // color: ['rgba(79,221,177)', 'rgba(255,96,131)'],
    legend: {
      data: props.chartData?.seriesData.map((item) => item.name),
      bottom: 10,

      icon: 'circle'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '10%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: props.chartData?.xAxisData,
        axisLine: {
          show: true,
          lineStyle: {
            width: 1,
            color: '#D9D9D9'
          }
        },
        axisLabel: {
          margin: 10,
          textStyle: {
            fontSize: '12',
            color: 'rgba(144,144,144)'
          }
        }
      }
    ],
    yAxis: [
      {
        name: '单位',
        type: 'value',
        axisLine: { show: false },
        axisTick: { show: false }, // 隐藏 Y 轴刻度线
        axisLabel: { color: 'rgba(144,144,144)' },
        splitLine: { lineStyle: { type: 'dashed', color: 'rgba(144,144,144,0.2)' } } // 网格虚线
      }
    ],
    series:
      props.chartData?.seriesData.map((item, index) => {
        return {
          name: item.name,
          type: 'bar',
          barWidth: '15%',
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0.4,
                  color: index == 0 ? 'rgba(79,106,187,1)' : 'rgba(79,196,255,1)'
                },
                {
                  offset: 1,
                  color: index == 0 ? 'rgba(79,106,187,1)' : 'rgba(79,196,255,1)'
                }
              ]),
              barBorderRadius: 11
            }
          },
          data: item.data
        }
      }) || []
  }
  chartInstance?.setOption(option, true)
  window.addEventListener('resize', () => {
    chartInstance?.resize()
  })
}
// 销毁图表实例
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
})
</script>
